<?php
namespace Todo\Model;
use Todo\Util\ArrayUtil;

/**
 * 内存model,初始化即从缓存加载全部，数据变化时，自动更新缓存
 * User: yepanpan
 * Date: 2016/8/8
 * Time: 17:59
 */
class MemoryModel extends BaseModel
{
    private $key = '';
    protected $order = 'id DESC';
    private $cached = array();

    protected function _initialize(){
        parent::_initialize();

        if(!$this->key) $this->key = 'memory_' . $this->tableName;
    }

    /**
     * 加载数据
     */
    protected function _loadData(){
        if($this->cached) return;

        $this->cached = S($this->key);
        if($this->cached) return;

        $this->_refresh();
    }

    /**
     * 查询全部
     * @param bool $mapField=false 映射的字段，为false则返回原始数据
     * @return array
     */
    public function findAll($mapField=false){
        $this->_loadData();
        return $mapField ? ArrayUtil::map($this->cached, 'id', $mapField) : $this->cached;
    }

    /**
     * 通过主键取数据
     * @param int $id 主键
     * @param string|boolean $field=true 字段，true表示返回全部
     * @return mixed
     */
    public function keyFind($id, $field=true){
        $row = $this->findByField('id', $id);
        return $field === true ? $row : $row[$field];
    }

    /**
     * 根据字段名和值，查询第一条匹配的数据
     * @param string $field 字段名
     * @param mixed $val 字段的值
     * @return mixed|null
     */
    public function findByField($field,$val){
        $this->_loadData();
        foreach ($this->cached as $row){
            if($row[$field] == $val) return $row;
        }
        return null;
    }

    /**
     * 根据字段过滤
     * @param string $field 字段名
     * @param mixed $val 字段的值
     * @return mixed|null
     */
    public function filterByField($field,$val){
        $list = array();
        $this->_loadData();
        foreach ($this->cached as $row){
            if($row[$field] == $val) $list[] = $row;
        }
        return $list;
    }


    //-------------------------------------即时重建缓存------------------------------
    protected function _refresh(){
        $this->cached = $this->order($this->order)->select();
        S($this->key,  $this->cached);
    }
    protected function _after_insert($data,$options) {
        $this->_refresh();
    }
    protected function _after_update($data,$options) {
        $this->_refresh();
    }
    protected function _after_delete($data,$options) {
        $this->_refresh();
    }
    //-------------------------------------即时重建缓存-------------------------------
}